﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using iSlideTools.LocalServer.Data;
using iSlideTools.LocalServer.Service;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http.Authentication;
using Microsoft.AspNetCore.Mvc;

namespace iSlideTools.LocalServer.Controllers
{
    public class AccountController : Controller
    {
        private readonly DataContext _dataContext;

        public AccountController(DataContext dataContext)
        {
            _dataContext = dataContext;
        }

        // Login: /<controller>/
        [AllowAnonymous]
        public IActionResult Login()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [AllowAnonymous]
        public async Task<IActionResult> Login(string userName, string password)
        {
            var pw = password.Hashing();

            var user = _dataContext.Users.FirstOrDefault(u => u.UserName == userName &&
                                                              u.Password == pw);
            if (user == null)
            {
                ViewBag.ErrorMessage = "用户名或密码错误";
                return View();
            }
            var claims = new List<Claim>
            {
                new Claim(ClaimTypes.Name, user.UserName),
                new Claim("password", user.Password)
            };
            if (!string.IsNullOrWhiteSpace(user.Role))
                claims.Add(new Claim(ClaimTypes.Role, user.Role));
            //init the identity instances 
            var userPrincipal = new ClaimsPrincipal(new ClaimsIdentity(claims, "User"));
            //signin 
            await HttpContext.Authentication.SignInAsync(AuthorizationInfo.Scheme, userPrincipal,
                new AuthenticationProperties
                {
                    ExpiresUtc = DateTime.UtcNow.AddMinutes(20),
                    IsPersistent = false,
                    AllowRefresh = false
                });
            return RedirectToAction("Index", "Home");
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Logout()
        {
            await HttpContext.Authentication.SignOutAsync(AuthorizationInfo.Scheme);
            return RedirectToAction(nameof(HomeController.Index), "Home");
        }

        public IActionResult Forbidden()
        {
            return View();
        }
    }
}